package cn.wyl.basic.util;

import cn.wyl.basic.jwt.JwtUtils;
import cn.wyl.basic.jwt.Payload;
import cn.wyl.basic.jwt.RsaUtils;
import cn.wyl.user.domain.Logininfo;
import cn.wyl.user.dto.LoginData;
import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

/**
 *  从请求头中获取加密token进而获取登录信息对象
 */
public class LoginContext {
    public static Logininfo getLogininfo(HttpServletRequest request) {

        String token = null;

        String url = request.getRequestURL().toString();
        if (url.contains("shop/export")) {
            token = url.substring(url.lastIndexOf("/") + 1);
        } else {

            //1.从请求头中获取token
            token = request.getHeader("token");
        }

        try {
            //3.如果有token，通过token获取redis的登录信息
            if (token != null) {
                //获取公钥
                PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());

                //将jwtToken解析成想要的数据：LoginData
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                if (payload != null) {//成功解密token，且没有过期
                    //获取登录信息对象
                    Logininfo logininfo = payload.getLoginData().getLogininfo();
                    return logininfo;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}




